package com.sfx.runner;

import com.sfx.domain.entity.Article;
import com.sfx.service.ArticleService;
import com.sfx.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sfx.constants.RedisConstants.ARTICLE_VIEWCOUNT_KEY;

/**
 * Created with IntelliJ IDEA.
 * Description: 在应用启动的时候把博客的浏览量存入到Redis中
 * User: sfx
 * Date: 2023-07-14
 * Time: 13:42
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    /**
     * 在应用启动的时候把博客的浏览量存入到Redis中
     */
    @Override
    public void run(String... args) throws Exception {
        //1.查询博客浏览量信息
        List<Article> articles = articleService.list();
        //2.以博客id作为key,浏览量作为Value存储到Redis中
        Map<String, Integer> map = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(),
                        article -> article.getViewCount().intValue()));

        redisCache.setCacheMap(ARTICLE_VIEWCOUNT_KEY, map);
    }
}